import { defineStore } from 'pinia'
import { User } from '@/types'
import router from '@/router'
import axios from 'axios'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    id: null as number | null,
    name: null as string | null,
    avatar: null as string | null,
    token: null as string | null,
    isAuthenticated: false
  }),
  getters: {
    user(): User {
      return {
        id: this.id,
        name: this.name,
        avatar: this.avatar,
        token: this.token
      }
    }
  },
  actions: {
    // 初始化状态，从localStorage加载用户数据
    initFromStorage() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      
      if (token && userInfo) {
        try {
          const user = JSON.parse(userInfo)
          this.id = user.id
          this.name = user.name
          this.avatar = user.avatar
          this.token = token
          this.isAuthenticated = true
        } catch (error) {
          console.error('Failed to parse user info:', error)
          // 如果解析失败，清除可能损坏的数据
          this.logout()
        }
      }
    },
    
    // 登录操作
    login(userData: { id: number; name: string; avatar: string; token: string }) {
      // 先更新状态
      this.id = userData.id
      this.name = userData.name
      this.avatar = userData.avatar
      this.token = userData.token
      this.isAuthenticated = true
      
      // 再保存到本地存储
      localStorage.setItem('token', userData.token)
      localStorage.setItem('userInfo', JSON.stringify({
        id: userData.id,
        name: userData.name,
        avatar: userData.avatar
      }))
    },
    
    // 退出登录
    logout() {
      // 先清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('captcha') // 同时清除验证码
      
      // 再清除状态
      this.id = null
      this.name = null
      this.avatar = null
      this.token = null
      this.isAuthenticated = false
      
      // 跳转到登录页
      router.push('/login')
    }
  }
}) 